package com.app.couponsharelife.ui.adapter

import androidx.databinding.DataBindingUtil
import androidx.core.content.ContextCompat
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.app.couponsharelife.R
import com.app.couponsharelife.data.bean.PrimarySortBean
import com.app.couponsharelife.databinding.SortTypeItemBinding
import com.app.couponsharelife.ui.listener.OnClickListener

/**
 * Created by guluwa on 2018/11/23.
 */
class SortTypeAdapter(var list: MutableList<PrimarySortBean.ListBean>, private val listener: OnClickListener) :
        androidx.recyclerview.widget.RecyclerView.Adapter<androidx.recyclerview.widget.RecyclerView.ViewHolder>() {

    private var selectPosition = 0

    fun setData(data: List<PrimarySortBean.ListBean>, position: Int) {
        selectPosition = position
        list.clear()
        list.addAll(data)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(DataBindingUtil.inflate(
                LayoutInflater.from(parent.context), R.layout.sort_type_item, parent, false))
    }

    override fun getItemCount(): Int {
        return list.size
    }

    override fun onBindViewHolder(holder: androidx.recyclerview.widget.RecyclerView.ViewHolder, position: Int) {
        (holder as ViewHolder).databinding.tvSort.text = list[position].name
        if (position == selectPosition) {
            holder.databinding.mIndicatorView.visibility = View.VISIBLE
            holder.databinding.tvSort.setTextColor(ContextCompat.getColor(holder.itemView.context, R.color.act_login_edit_text_text_color))
            holder.databinding.root.setBackgroundColor(ContextCompat.getColor(holder.itemView.context, R.color.act_bg_color))
        } else {
            holder.databinding.mIndicatorView.visibility = View.GONE
            holder.databinding.tvSort.setTextColor(ContextCompat.getColor(holder.itemView.context, R.color.act_main_bot_nav_normal_text_color))
            holder.databinding.root.setBackgroundColor(ContextCompat.getColor(holder.itemView.context, R.color.white))
        }
    }

    inner class ViewHolder(val databinding: SortTypeItemBinding) : androidx.recyclerview.widget.RecyclerView.ViewHolder(databinding.root) {
        init {
            databinding.root.setOnClickListener {
                if (adapterPosition != -1 && selectPosition != adapterPosition) {
                    notifyItemChanged(selectPosition)
                    selectPosition = adapterPosition
                    notifyItemChanged(selectPosition)
//                    listener.click(selectPosition, list[selectPosition].id as Any)
                    listener.click(selectPosition, list[adapterPosition])
                }
            }
        }
    }
}